package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.bean.UserLoginBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/12/12 13:50
 */
public class Dws_04_DwsUserUserLoginWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_04_DwsUserUserLoginWindow().init(
            4004,
            2,
            "Dws_04_DwsUserUserLoginWindow",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        // 1. 过滤登陆记录
        SingleOutputStreamOperator<JSONObject> loginLogStream = filterLoginLog(stream);
        // 2. 转成 pojo
        SingleOutputStreamOperator<UserLoginBean> beanStream = parseToPojo(loginLogStream);
        // 3. 开窗聚合
        SingleOutputStreamOperator<UserLoginBean> result = windowAndAgg(beanStream);
        // 4. 写出到 clickhouse
        writeToClickHouse(result);
        
    }
    private void writeToClickHouse(SingleOutputStreamOperator<UserLoginBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_user_user_login_window", UserLoginBean.class));
    }
    
    private SingleOutputStreamOperator<UserLoginBean> windowAndAgg(SingleOutputStreamOperator<UserLoginBean> beanStream) {
       return beanStream
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<UserLoginBean>() {
                    @Override
                    public UserLoginBean reduce(UserLoginBean value1,
                                                UserLoginBean value2) throws Exception {
                        value1.setUuCt(value1.getUuCt() + value2.getUuCt());
                        value1.setBackCt(value1.getBackCt() + value2.getBackCt());
                        return value1;
                    }
                },
                new AllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow w,
                                      Iterable<UserLoginBean> values,
                                      Collector<UserLoginBean> out) throws Exception {
                        UserLoginBean bean = values.iterator().next();
                        bean.setStt(AtguiguUtil.toDatTime(w.getStart()));
                        bean.setEdt(AtguiguUtil.toDatTime(w.getEnd()));
    
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<UserLoginBean> parseToPojo(SingleOutputStreamOperator<JSONObject> stream) {
        return stream
            .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
            .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {
                
                private ValueState<String> lastLoginDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastLoginDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastLoginDate", String.class));
                }
                
                @Override
                public void processElement(JSONObject value,
                                           Context ctx,
                                           Collector<UserLoginBean> out) throws Exception {
                    Long ts = value.getLong("ts");
                    String today = AtguiguUtil.tsToDate(ts);
                    
                    // 先找到今天的这个用户的首次登录记录
                    String lastLoginDate = lastLoginDateState.value();
                    
                    Long uuCt = 0L;
                    Long backCt = 0L;
                    // 今天和最后一次是否相等
                    if (!today.equals(lastLoginDate)) {
                        lastLoginDateState.update(today);
                        uuCt = 1L;
                        
                        // 如果是这个用户今天首次登录, 再判断是否为 7日回流用户
                        if (lastLoginDate != null) {
                            // 2022-12-10 -> 2022-12-10 00:00:00
                            // 2022-12-11 10:09:22  -> 2022-12-11 00:00:00
                            // 1200 / 1000 = 1
                            Long lastLoginTs = AtguiguUtil.dateToTs(lastLoginDate);
                            if ((ts - lastLoginTs) / 1000 / 60 / 60 / 24 > 7) {
                                backCt = 1L;
                            }
                            
                        }
                    }
                    
                    if (uuCt > 0) {
                        out.collect(new UserLoginBean("", "",
                                                      backCt, uuCt,
                                                      ts
                        ));
                    }
                    
                }
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> filterLoginLog(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .filter(new FilterFunction<JSONObject>() {
                @Override
                public boolean filter(JSONObject value) throws Exception {
                    String lastPageId = value.getJSONObject("page").getString("last_page_id");
                    String uid = value.getJSONObject("common").getString("uid");
                    return (null == lastPageId || "login".equals(lastPageId)) && uid != null;
                }
            });
    }
    
}
/*
用户登录各窗口汇总表
从 Kafka 页面日志主题读取数据，统计七日回流用户和当日独立用户数。
数据源:
    页面日志
    
登陆数据(登陆页面数据):
    登陆情况:
    1. 自动登陆
        last_page_id == null && uid != null
    2. 浏览的过程中, 跳转到登录页面, 然后再登录
        a ->login->b
        找到 b 页面:  last_page_id=login && uid != null
        
当日独立用户数
    状态存储年月日
七日回流用户
    今天登录用户
        今天和状态中的登录日期相差 7 就是 7 日回流
     

开窗聚合
*/